package com.hisense.ovcloud.warehouse.routers;

import cn.hutool.json.JSONUtil;
import com.hisense.ovcloud.commons.configs.validator.BaseRouterConfiguration;
import com.hisense.ovcloud.commons.tools.LocalLFUCacheUtil;
import com.hisense.ovcloud.warehouse.dto.common.DeviceInfoInCache;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import static org.springframework.web.reactive.function.server.RequestPredicates.path;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;

@Configuration
public class CacheRoutersConfiguration extends BaseRouterConfiguration {
    final
    LocalLFUCacheUtil<DeviceInfoInCache> deviceCache;

    public CacheRoutersConfiguration(@Qualifier("deviceCache") LocalLFUCacheUtil<DeviceInfoInCache> deviceCache) {
        this.deviceCache = deviceCache;
    }

    @Bean
    public RouterFunction<ServerResponse> cacheRoutes() {
        return RouterFunctions.nest(path("/cache"),
                route()
                        .GET("/get/{wifiId}", req -> ServerResponse.ok().body(Mono.just(JSONUtil.toJsonStr(deviceCache.getFromCache(req.pathVariable("wifiId")))),
                                String.class))
                        .GET("/batchGet/{wifiIdList}", req -> ServerResponse.ok().body(Mono.just(JSONUtil.toJsonStr(deviceCache.mGetFromCache(req.pathVariable("wifiIdList")))),
                                String.class))
                        .GET("/delete/{wifiId}", req -> ServerResponse.ok().body(Mono.just(deviceCache.deleteFromCache(req.pathVariable("wifiId"))),
                                Boolean.class))
                        .GET("/mdelete/{wifiIdList}", req -> ServerResponse.ok().body(Mono.just(deviceCache.mDeleteFromCache(req.pathVariable("wifiIdList"))),
                                Boolean.class))
                        .GET("/size", req -> ServerResponse.ok().body(Mono.just(deviceCache.cacheSize()),
                                Integer.class))
                        .build());
    }
}
